from django.db import models
from django.contrib.auth import authenticate
from django.contrib.auth.models import AbstractUser
# Create your models here.
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadData
from django.conf import settings
class User(AbstractUser):
    mobile = models.CharField(max_length=11,
                              unique=True,
                              verbose_name='手机号')
    email_active = models.BooleanField(default=False,
                                       verbose_name='邮箱验证状态')

    class Meta:
        db_table = 'tb_users'
        verbose_name = '用户'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.username

        # 新增 email_active 字段
        # 用于记录邮箱是否激活, 默认为 False: 未激活
    def generate_verify_email_url(self):
        '''我们将url加密方法放到用户模型类之中通过用户模型类来区分'''
        #生成加密对象
        token_serializer = Serializer(settings.SECRET_KEY, expires_in=60*60*24)
        #准备要加密的数据
        data = {'user_id': self.id, 'email': self.email}
        #生成token
        token = token_serializer.dumps(data).decode()
        #与url拼接
        verify_url = settings.EMAIL_VERIFY_URL + token
        #返回verify_url
        return verify_url

    #定义解密方法
    @staticmethod
    def cleck_verify_email_url(token):
        '''通过这个方法对token解密成功后返回user'''
        #创建解密对象
        token_cleck = Serializer(settings.SECRET_KEY, expires_in=60*60*12)
        #解密token
        try:
            data = token_cleck.loads(token)
        except BadData:
            return None
        else:
            #成功后我们提起参数校验参数
            user_id = data.get('user_id')
            email = data.get('email')


        #尝试在数据库中获取用户对象
        try:
            user = User.objects.get(id=user_id,
                                    email=email)
        except Exception as e:
            return None
        else:
            return user
